package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;

/**
 * 采用无需实现类只使用接口制作代理对象
 */
public class FacadeProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("proxy class: " + proxy.getClass().getTypeName());

        if (isDefaultMethod(method)) {
            System.out.println("default method .......");
        }

        System.out.println("接口方法调用开始");
        //执行方法
        System.out.println("method toGenericString:" + method.toGenericString());
        System.out.println("method name:" + method.getName());
        System.out.println("method args:" + (String) args[0]);
        System.out.println("接口方法调用结束");
        return "调用返回值";
    }

    public static <T> T newMapperProxy(Class<T> mapperInterface) {
        ClassLoader classLoader = mapperInterface.getClassLoader();
        Class<?>[] interfaces = new Class[]{mapperInterface};
        FacadeProxy proxy = new FacadeProxy();
        return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
    }


    /**
     * Backport of java.lang.reflect.Method#isDefault()
     */
    private boolean isDefaultMethod(Method method) {
        return (method.getModifiers()
                & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC
                && method.getDeclaringClass().isInterface();
    }


}
